package com.xx.happychatboot.middleware.springsecurity.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证处理器
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isBlank(authException.getMessage())) {
            result.put("msg", "请先认证");
        } else {
            result.put("msg", authException.getMessage());
        }
        result.put("status", HttpServletResponse.SC_UNAUTHORIZED);

        String jsonResponse = new ObjectMapper().writeValueAsString(result);
        response.getWriter().println(jsonResponse);
    }
}
